import base64
import json
import re
from urllib.parse import unquote
import requests


class BossDecrypt:
    """
    BOSS直聘数据解密工具
    注意：BOSS直聘的encryptId通常是经过多重加密的，完全解密可能需要逆向工程
    """

    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update(
            {
                "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
            }
        )

    def decode_base64(self, encrypted_id):
        """
        尝试Base64解码
        :param encrypted_id: 加密的ID
        :return: 解码结果
        """
        try:
            # 尝试直接解码
            decoded = base64.b64decode(encrypted_id)
            return decoded.decode("utf-8", errors="ignore")
        except:
            try:
                # 尝试URL安全的Base64解码
                decoded = base64.urlsafe_b64decode(
                    encrypted_id + "=" * (4 - len(encrypted_id) % 4)
                )
                return decoded.decode("utf-8", errors="ignore")
            except:
                return None

    def url_decode(self, encrypted_id):
        """
        URL解码
        :param encrypted_id: 加密的ID
        :return: 解码结果
        """
        try:
            return unquote(encrypted_id)
        except:
            return None

    def extract_job_id_from_url(self, url):
        """
        从URL中提取职位ID
        :param url: BOSS直聘职位URL
        :return: 职位ID
        """
        # 匹配常见的BOSS直聘URL模式
        patterns = [
            r"/job_detail/([^/?]+)",
            r"/job_detail/([^/?]+)\.html",
            r"jobId=([^&]+)",
            r"encryptId=([^&]+)",
        ]

        for pattern in patterns:
            match = re.search(pattern, url)
            if match:
                return match.group(1)
        return None

    def get_job_detail_by_encrypt_id(self, encrypt_id):
        """
        通过encryptId获取职位详情
        :param encrypt_id: 加密的职位ID
        :return: 职位详情
        """
        try:
            # BOSS直聘的API接口（可能需要更新）
            api_url = f"https://www.zhipin.com/wapi/zpgeek/job/detail.json"
            params = {"encryptId": encrypt_id, "source": "web"}

            response = self.session.get(api_url, params=params)
            if response.status_code == 200:
                return response.json()
            else:
                return None
        except Exception as e:
            print(f"获取职位详情失败: {e}")
            return None

    def analyze_encrypt_id(self, encrypt_id):
        """
        分析加密ID的结构
        :param encrypt_id: 加密的ID
        :return: 分析结果
        """
        analysis = {
            "original_id": encrypt_id,
            "length": len(encrypt_id),
            "base64_decoded": None,
            "url_decoded": None,
            "possible_patterns": [],
        }

        # Base64解码尝试
        base64_result = self.decode_base64(encrypt_id)
        if base64_result:
            analysis["base64_decoded"] = base64_result

        # URL解码尝试
        url_result = self.url_decode(encrypt_id)
        if url_result:
            analysis["url_decoded"] = url_result

        # 分析可能的模式
        if re.match(r"^[A-Za-z0-9+/=]+$", encrypt_id):
            analysis["possible_patterns"].append("Base64编码")

        if "%" in encrypt_id:
            analysis["possible_patterns"].append("URL编码")

        if len(encrypt_id) == 32:
            analysis["possible_patterns"].append("MD5哈希")

        if len(encrypt_id) == 64:
            analysis["possible_patterns"].append("SHA256哈希")

        return analysis

    def decrypt_encrypt_id(self, encrypt_id):
        """
        尝试解密encryptId
        :param encrypt_id: 加密的ID
        :return: 解密结果
        """
        print(f"正在分析encryptId: {encrypt_id}")

        # 分析ID结构
        analysis = self.analyze_encrypt_id(encrypt_id)
        print(f"ID长度: {analysis['length']}")
        print(f"可能的编码模式: {', '.join(analysis['possible_patterns'])}")

        # 尝试获取职位详情
        job_detail = self.get_job_detail_by_encrypt_id(encrypt_id)
        if job_detail:
            print("成功获取职位详情:")
            print(json.dumps(job_detail, ensure_ascii=False, indent=2))
            return job_detail

        # 如果无法直接获取，返回分析结果
        print("无法直接解密，返回分析结果:")
        return analysis


def demo_decrypt():
    """演示解密功能"""
    print("=== BOSS直聘encryptId解密演示 ===")

    decryptor = BossDecrypt()

    # 示例encryptId（请替换为实际的ID）
    sample_encrypt_id = "example_encrypt_id_here"

    print("请输入要解密的encryptId（或按回车使用示例）:")
    user_input = input().strip()

    if user_input:
        encrypt_id = user_input
    else:
        encrypt_id = sample_encrypt_id
        print(f"使用示例ID: {encrypt_id}")

    # 执行解密
    result = decryptor.decrypt_encrypt_id(encrypt_id)

    print("\n=== 解密结果 ===")
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    demo_decrypt()
